package org.springframework.beans.factory.context.annotation;

import org.springframework.beans.factory.config.AnnotationBeanNameGenerator;
import org.springframework.beans.factory.config.BeanNameGenerator;
import org.springframework.beans.factory.support.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;

import java.util.Objects;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/14
 */
public class AnnotatedBeanDefinitionReader {
    //bd注册中心，负责bd的注册
    private final BeanDefinitionRegistry registry;
    //beanName生成器
    private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
        Objects.requireNonNull(registry, "BeanDefinitionRegistry must not be null");
        this.registry = registry;
        //去注册三个bd，两个beanPostProcessor,一个BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor
        AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    }

    public final BeanDefinitionRegistry getRegistry() {
        return this.registry;
    }


    public void register(Class<?>[] annotatedClasses) {
        for (Class<?> annotatedClass : annotatedClasses) {
            registerBean(null,annotatedClass);
        }
    }

    public void registerBean(String name,Class<?> annotatedClass) {
        doRegisterBean(name,annotatedClass);
    }

    protected void doRegisterBean(String name,Class<?> annotatedClass) {

        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);

        String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd));
        //@Role @Scope @Lazy
        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);

        registry.registerBeanDefinition(beanName,abd);
    }
}
